package com.stylefeng.guns.modular.huamao.service.impl;

import com.stylefeng.guns.modular.huamao.common.GetOrderNum;
import com.stylefeng.guns.modular.huamao.dao.*;
import com.stylefeng.guns.modular.huamao.model.*;
import com.stylefeng.guns.modular.huamao.result.AppResult;
import com.stylefeng.guns.modular.huamao.result.Result;
import com.stylefeng.guns.modular.huamao.service.*;
import com.stylefeng.guns.modular.huamao.util.*;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import com.stylefeng.guns.rest.common.constants.RabbitConstants;
import groovy.lang.ObjectRange;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * <p>
 * 购物车表 服务实现类
 * </p>
 *
 * @author caody123
 * @since 2018-05-10
 */
@Service
public class SktCartsServiceImpl extends ServiceImpl<SktCartsMapper, SktCarts> implements ISktCartsService {

	@Autowired
	SktCartsMapper sktCartsMapper;
	@Autowired
    private IAccountService accountService;
	@Autowired
    private ISktOrdersService sktOrdersService;
	@Autowired
    private ISktOrderGoodsService sktOrderGoodsService;
	@Autowired
	private IGoodsService goodsService;
	@Autowired
	private GoodsMapper goodsMapper;
	@Autowired
	private IMessagesService messagesService;
	@Autowired
	private SktShopsMapper sktShopsMapper;
	@Autowired
	private SpecItemsMapper specItemsMapper;
	@Autowired
	private UsersAddressMapper usersAddressMapper;
	@Autowired
	private SktShopFreightsMapper sktShopFreightsMapper;
	@Autowired
	private SktOrdersMapper sktOrdersMapper;
	@Autowired
    private AccountMapper accountMapper;
	@Autowired
    private PaySceneMapper paySceneMapper;
	@Autowired
	private ISktOrdersExtensionService sktOrdersExtensionService;
	@Autowired
	private ILogScoreService logScoreService;
	@Autowired
    private SktSysConfigsMapper sysConfigsMapper;
	@Autowired
	private SpecCatsMapper specCatsMapper;
	@Autowired
	private IGoodsSpecsService goodsSpecsService;
	@Autowired
	private ISktAreasService sktAreasService;
	@Autowired
	private GoodsSpecsMapper goodsSpecsMapper;
	@Autowired
	private CacheUtil cacheUtil;
	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private RabbitSender rabbitSender;


	/**
	 * 根据用户id查询订单商品表(返回规格信息)
	 */
	@Override
	public List<Map<String,Object>> selectCartsByuserId(Map<String,Object> stringObjectMap) {

		List<Map<String,Object>> list =  sktCartsMapper.selectCartsByuserId(stringObjectMap);
		for (Map<String,Object> map:list){
			Integer isSpec = Integer.parseInt(map.get("isSpec").toString());
			List<Map<String,Object>> mapList = new ArrayList<Map<String, Object>>();
			if (isSpec == 1){
				Integer goodsSpecId  = Integer.parseInt(map.get("goodsSpecId").toString());
				GoodsSpecs  goodsSpecs =  new GoodsSpecs();

				goodsSpecs = goodsSpecsService.selectById(goodsSpecId);

				String specIds  = goodsSpecs.getSpecIds();


				if(specIds != null){
					String[] parts = specIds.toString().split(":");

					for (int i = 0 ; i <parts.length ; i++ ) {
						Map<String,Object> objectMap = new HashMap<String, Object>();
						Integer itemId = Integer.parseInt(parts[i]);
						SpecItems specItems = new SpecItems();
						specItems = specItemsMapper.selectById(itemId);
						objectMap.put("itemName",specItems.getItemName());
						SpecCats specCats =  new SpecCats();
						specCats = specCatsMapper.selectById(specItems.getCatId());
						objectMap.put("catName",specCats.getCatName());
						mapList.add(objectMap);
					}
				}
				map.put("specList",mapList);

			}

			map.put("specList",mapList);



		}

		return list;
	}
	
	/**
	 * 购物车结算时操作
	 */
	@Override
	@Transactional
	public JSONObject cartsSettlement(Integer userId,BigDecimal goodsMoney,List<Map<String,Object>> param){
		JSONObject result = new JSONObject();
		/**
		 * 商品对应的shopid
		 */
		List<Integer> listShopId  = new ArrayList<Integer>();
		/**
		 * 去重之后的shopid
		 */
		List<Integer> rlistShopId  = new ArrayList<Integer>();

		/**
		 * 用来校验页面传来的值是否准确
		 */
		BigDecimal  totalMoney = new BigDecimal(0.00);
		BigDecimal  totalPayKaiyuan = new BigDecimal(0.00);
		BigDecimal  totalPayShopping = new BigDecimal(0.00);


		/**
		 * 判断是否都没有选中
		 */
		int allCheck = 0;
		String settlementLock = "settlementLock"+userId;
		RedisLock redisLock = new RedisLock(redisTemplate, settlementLock);
		try {
			/**
			 * 原子操作
			 */
			if (redisLock.lock()){
				/**
				 * 去掉重复的商家id
				 */
				for(Map<String,Object> map:param){

					Goods saveGoods = new Goods();
					int cartId = Integer.parseInt(String.valueOf(map.get("cartId")));
					int goodsId = Integer.parseInt(String.valueOf(map.get("goodsId")));
					int cartNum = Integer.parseInt(String.valueOf(map.get("cartNum")));
					int isCheck = Integer.parseInt(String.valueOf(map.get("isCheck")));
					allCheck += isCheck;
					/**
					 * 批量更新ischeck状态值
					 */
					SktCarts sktCarts = new SktCarts();
					sktCarts.setCartId(cartId);
					sktCarts.setIsCheck(isCheck);
					sktCartsMapper.updateById(sktCarts);

					Goods goods = goodsService.selectById(goodsId);
					if (goods.getIsSale()==0 ){
						result.put("success", false);
						result.put("obj","您选择的商品中有已下架商品，请重新选择!");
						return result;
					}
					if (goods.getGoodsStatus()!=1){
						result.put("success", false);
						result.put("obj","您选择的商品中有商品违规或正在审核中");
						return  result;
					}
					if (goods.getDataFlag()==-1){
						result.put("success", false);
						result.put("obj","您选择的商品中有商品已经失效");
						return  result;
					}
					Integer shopId=goods.getShopId();
					SktShops shops = sktShopsMapper.selectById(shopId);
					Integer shopUserId = shops.getUserId();
					if(userId.equals(shopUserId)){
						result.put("success", false);
						result.put("obj","不可以购买自己店铺的商品");
						return  result;
					}
					if (shops.getShopStatus()==0){
						result.put("success", false);
						result.put("obj","您选择的商品中有商品所属商家已关闭");
						return  result;
					}
					if (shops.getDataFlag()==-1){
						result.put("success", false);
						result.put("obj","您选择的商品中有商家已失效");
						return  result;
					}
					/**
					 * 查询规格下的物品库存，如果没有规格，用商品总库存
					 */
					SktCarts rsktCarts = new SktCarts();
					rsktCarts = this.selectById(cartId);
					Integer Stock = 0;
					String redisKey = "redis_key:stock:" + goodsId;
					System.out.println("aaaaaa:"+!cacheUtil.isKeyInCache(redisKey));
					if(!cacheUtil.isKeyInCache(redisKey)){
						/**
						 * 缓存的数据格式
						 *redisKey:{
						 *     "goodsStock":goodsStock,
						 *     "isSpec":true/false,
						 *     "spec": {
						 *         specId:specStock,
						 *     }
						 *}
						 */
						JSONObject jmap = new JSONObject();

						Goods jgoods = new Goods();
						jgoods = goodsService.selectById(goodsId);
						jmap.put("goodsStock",goods.getGoodsStock());
						if(rsktCarts.getGoodsSpecId().equals("0")){
							jmap.put("isSpec",false);
						}else{
							jmap.put("isSpec",true);
							JSONObject specsMap = new JSONObject();
							GoodsSpecs goodsSpecs1 =  new GoodsSpecs();
							goodsSpecs1.setGoodsId(goodsId);
							EntityWrapper<GoodsSpecs> entityWrapper =  new EntityWrapper<GoodsSpecs>(goodsSpecs1);
							List<GoodsSpecs> goodsSpecsList  = goodsSpecsService.selectList(entityWrapper);
							for(GoodsSpecs temp:goodsSpecsList){
								specsMap.put(temp.getId().toString(),temp.getSpecStock());
							}
							jmap.put("spec",specsMap);
						}

						cacheUtil.set(redisKey,jmap, Long.valueOf(60*30));
					};
					/**
					 * 从缓存中获取库存
					 */
					//String redisKey = "redis_key:stock:" + goodsId;

					JSONObject jsonObject = JSONObject.parseObject(cacheUtil.simpleGet(redisKey).toString());
					if(jsonObject.getBoolean("isSpec")){
						JSONObject spec = jsonObject.getJSONObject("spec");
						Stock = spec.getInteger(rsktCarts.getGoodsSpecId());
					}else{
						Stock = jsonObject.getInteger("goodsStock");
					};

					/**
					 * 只有选中商品才会做操作
					 */
					if(isCheck == 1){
						if(Stock.intValue() >= cartNum){
							listShopId.add(goods.getShopId());
							GoodsSpecs goodsSpecs = new GoodsSpecs();

							/**
							 * 判断是否有规格
							 */
							if(rsktCarts.getGoodsSpecId().equals("0")){
								totalMoney = totalMoney.add(goods.getShopPrice().multiply(new BigDecimal(cartNum)));
							}else{
								goodsSpecs  = goodsSpecsService.selectById(rsktCarts.getGoodsSpecId());
								totalMoney =  totalMoney.add(goodsSpecs.getSpecPrice().multiply(new BigDecimal(cartNum)));
							}
							totalPayKaiyuan=totalPayKaiyuan.add(goods.getPayKaiyuan().multiply(new BigDecimal(cartNum)));
							totalPayShopping=totalPayShopping.add(goods.getPayShopping().multiply(new BigDecimal(cartNum)));
						}else{
							/**
							 * 如果是立即购买的物品，应该删除对应购物车的物品信息
							 */
							SktCarts  sktCarts1 = new SktCarts();
							sktCarts1 = sktCartsMapper.selectById(cartId);
							if(sktCarts1.getIsDirect() == 1){
								sktCartsMapper.deleteById(cartId);
							}
							result.put("obj","库存数量不足");
							result.put("success", false);
							List<Integer> usersIds=new ArrayList<Integer>();
							usersIds.add(goods.getShopId());
							messagesService.addMessages(1,1,usersIds,"您的商品"+goods.getGoodsName()+"库存数量不足,请尽快补货",null);

							return result;
						}
					}


				}
				if(allCheck == 0){
					result.put("obj","请选择购物车物品!");
					result.put("success", false);
					return result;
				}
				if(!totalMoney.equals(goodsMoney)){
					result.put("obj","结算失败!");
					result.put("success", false);
					return result;
				}

				/**
				 *去重后的shopid列表
				 */
				rlistShopId = this.removeDuplicate(listShopId);

				/**
				 * 用来接收生成的返回值
				 */
				List<Integer> sktOrdersListId = new ArrayList<Integer>();

				/**
				 * 存贮订单id与店铺id的关系列表
				 */
				List<Map<String,Integer>> mapList = new ArrayList<Map<String,Integer>>();
				String orderunique  = StringUtils.getOrderIdByTime("2"); //流水号
				for(Integer llistShopId :rlistShopId){
					/**
					 * 订单id跟店铺id的map
					 */
					Map<String,Integer> SOMap = new HashMap<String, Integer>();
					/**
					 * 获取订单号跟流水账号
					 */
					String orderNo = StringUtils.getOrderIdByTime("2");
					rabbitSender.sendMessage(RabbitConstants.MQ_EXCHANGE_ORDER,RabbitConstants.MQ_ROUTING_KEY_ORDER,orderNo);
					String redisKey = "redis_key:orderNo:" + orderNo;
					cacheUtil.set(redisKey,orderNo,Long.valueOf(60*30));

					/**
					 * 获取会员账户
					 */
					Account account = new Account();
					Account accountr = new Account();
					account.setUserId(userId);
					EntityWrapper<Account> ewacc=new EntityWrapper<Account>();
					ewacc.setEntity(account);
					accountr = accountService.selectOne(ewacc);

					/**
					 * 添加订单记录并获取订单id
					 */
					@SuppressWarnings("unused")
					Date date = new Date();
					SktOrders sktOrders = new SktOrders();
					sktOrders.setOrderNo(orderNo);
					sktOrders.setUserId(userId);
					sktOrders.setOrderunique(orderunique);
					sktOrders.setCash(BigDecimal.ZERO);
					sktOrders.setOrderStatus(-2);
					sktOrders.setGoodsMoney(goodsMoney);
					sktOrders.setCreateTime(date);
					sktOrders.setShopId(llistShopId);
					sktOrders.setKaiyuan(totalPayKaiyuan);
					sktOrders.setTotalShopping(totalPayShopping);

					sktOrdersService.insert(sktOrders);

					sktOrdersListId.add(sktOrders.getOrderId());

					SOMap.put("shopId",llistShopId);
					SOMap.put("orderId",sktOrders.getOrderId());

					mapList.add(SOMap);
					List<Integer> usersIds=new ArrayList<Integer>();
					usersIds.add(llistShopId);
					messagesService.addMessages(1,1,usersIds,"您有一笔新的订单【"+orderNo+"】待处理.",null);

				}

				/**
				 * 添加订单货物内容
				 */
				for(Map<String,Object> map:param){
					Integer cartId = Integer.parseInt(String.valueOf(map.get("cartId")));
					Integer shopId = Integer.parseInt(String.valueOf(map.get("shopId")));
					Integer orderId = 0;
					/**
					 * 遍历封装的关系列表，通过shopId获取orderId，
					 * 貌似不能从订单表里面查询，订单表里面对应的关系有点多。
					 * 在一个操作中是一一对应的关系，在数据库中就不是了
					 */
					for (Map<String,Integer> somap:mapList){
						if(shopId.equals(somap.get("shopId"))){
							orderId = somap.get("orderId");
						}
					}

					Map<String,Integer> paramMap = new HashMap<String,Integer>();
					paramMap.put("cartId",cartId);
					/**
					 * 从购物车获取订单商品，添加到订单商品表。只有选中的物品才能被处理
					 */
					SktOrderGoods sktOrderGoods = new SktOrderGoods();
					SktCarts sktCarts = new SktCarts();
					sktCarts = this.selectById(cartId);
					/**
					 * 如果没有规格id，就查询商品的信息
					 */
					if(sktCarts.getGoodsSpecId().equals("0")){
						sktOrderGoods = sktCartsMapper.selectCartsSettlementByuserId(paramMap);
					}else{
						sktOrderGoods = sktCartsMapper.selectCartsSpecsByuserId(paramMap);
					}

					if(sktOrderGoods == null) {

					}else{
						//查询商品id查询自营店商品积分
						Integer payScore = sktOrderGoods.getGoodsId();
						Goods goods = goodsMapper.selectById(payScore);
						if(!MSGUtil.isBlank(goods)){
							sktOrderGoods.setPayScore(goods.getPayScore()*sktOrderGoods.getGoodsNum());
						}else{
							sktOrderGoods.setPayScore(0);
						}
						sktOrderGoods.setOrderId(orderId);
						sktOrderGoodsService.insert(sktOrderGoods);
					}


				}
				/**
				 * 获取积分（cartId对应一条物品信息）
				 */
				BigDecimal cartScore = new BigDecimal("0");

				for(Map<String,Object> tempMap:param){
					BigDecimal tempScore;
					BigDecimal goodsPrice;
					int cartId = Integer.parseInt(String.valueOf(tempMap.get("cartId")));
					Map<String,Integer> paramMap = new HashMap<String,Integer>();
					paramMap.put("cartId",cartId);
					SktOrderGoods sktOrderGoods = sktCartsMapper.selectCartsSettlementByuserId(paramMap);
					/**
					 * 只有选中的物品才能增加积分
					 */
					if (sktOrderGoods != null){
						tempScore = sktOrderGoods.getScore();
						cartScore = cartScore.add(tempScore);
					}

				}

				/**
				 * 选择性删除购物车信息
				 * 根据传来购物车的物品删除
				 * 减少相应的库存
				 */
				for(Map<String,Object> map:param){

					SktCarts sktCarts = new SktCarts();
					int cartId = Integer.parseInt(String.valueOf(map.get("cartId")));
					int goodsId = Integer.parseInt(String.valueOf(map.get("goodsId")));
					int cartNum = Integer.parseInt(String.valueOf(map.get("cartNum")));
					int isCheck = Integer.parseInt(String.valueOf(map.get("isCheck")));


					/**
					 * 如果选中的话才会删除
					 */
					if(isCheck == 1){
						sktCarts = this.selectById(cartId);
						/**
						 * 删除购物对应内容
						 * 如果数量（cartNum）跟购物车的数量相等那么删除此条记录
						 * 如果数量（cartNum）小于购物车的数量那么更新数量
						 */
						if(cartNum < sktCarts.getCartNum()){
							int tempNum = sktCarts.getCartNum() - cartNum;
							sktCarts.setCartNum(tempNum);
							this.updateById(sktCarts);
						}else{
							this.deleteById(cartId);
						}

						/**
						 *减少缓存的中的库存
						 */
						String redisKey = "redis_key:stock:" + goodsId;
						JSONObject jsonObject = JSONObject.parseObject(cacheUtil.simpleGet(redisKey).toString());
						if(jsonObject.getBoolean("isSpec")){
							jsonObject.put("goodsStock",jsonObject.getInteger("goodsStock")-cartNum);
							JSONObject  specObj = jsonObject.getJSONObject("spec");
							specObj.put(sktCarts.getGoodsSpecId(),specObj.getInteger(sktCarts.getGoodsSpecId())-cartNum);
						}else{
							jsonObject.put("goodsStock",jsonObject.getInteger("goodsStock")-cartNum);
						}
						cacheUtil.set(redisKey,jsonObject,Long.valueOf(60*30));

					}


				}
				result.put("sktOrdersListId", sktOrdersListId);
				result.put("cartScore",cartScore);
				result.put("success", true);
			}

		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			result.put("obj","结算失败");
			result.put("success", false);
		}finally {
			redisLock.unlock();
		}
		return result;

	}

	@Override
	public Map<String,Object> appCarts(Integer userId) {
		Map<String,Object> maps = new HashMap<String,Object>();
		List<Map<String,Object>> list4 = new ArrayList<Map<String,Object>>();
		//先查询用户购物车中的商品在那几个店铺(去重)
		List<Map<String,Object>> list = sktShopsMapper.appFindShops(userId);
		if(list == null || list.size() <= 0){
			Map<String,Object> map = new HashMap<String,Object>();
			maps.put("msg","您的购物车为空，快去添加商品吧！");
			maps.put("code",0);
			return maps;
		}
		for (Map<String,Object> map2:
				list) {
			Map<String,Object> map = new HashMap<String,Object>();
			//将店铺名称存到map中
			String shopName = (String)map2.get("shopName");
			map.put("catName",shopName);
			Map<String,Object> map3 = new HashMap<String,Object>();
			Integer shopId = (Integer)map2.get("shopId");
			map3.put("shopId",shopId);
			map3.put("userId",userId);
			//通过店铺id查询用户购物车中这个店铺的商品
			List<Map<String,Object>> list2 = sktCartsMapper.appFindGoodsByShopIdAll(map3);
			for (Map<String,Object> map4:
					list2) {
				/**
				 * 获取商品规格数据
				 */

				if (!"".equals(map4.get("specIds"))&& map4.get("specIds")!=null){
					String specIdses = map4.get("specIds").toString();
					GoodsSpecs goodsSpecs = new GoodsSpecs();
					goodsSpecs.setGoodsId(Integer.parseInt(map4.get("goodsId").toString()));
					goodsSpecs.setSpecIds(specIdses);
					EntityWrapper<GoodsSpecs> gsew = new EntityWrapper<GoodsSpecs>(goodsSpecs);
					GoodsSpecs resultgs = new GoodsSpecs();
					if (gsew!=null){
						resultgs = goodsSpecsService.selectOne(gsew);
					}
					if (resultgs!=null){

						map4.put("specPrice",resultgs.getSpecPrice());
						map4.put("shopPrice",resultgs.getSpecPrice());
						map4.put("specStock",resultgs.getSpecStock());
						map4.put("specIds",resultgs.getSpecIds());
					}else{
						map4.put("specPrice",map4.get("shopPrice").toString());
						map4.put("specStock","0");
						map4.put("specIds","0");
					}
				}else {
					map4.put("specPrice",map4.get("shopPrice").toString());
					map4.put("specStock","0");
					map4.put("specIds","0");
				}
				map4.put("payKaiyuan",map4.get("payKaiyuan").toString());//所需华宝
				map4.put("payShopping",map4.get("payShopping").toString());//所需优惠券
				//用于拼接商品规格字符串
				String specName = "";
				//判断是否有规格
				Integer isSpec = (Integer)map4.get("isSpec");
				if(isSpec == 1){

					String specIds = (String)map4.get("specIds");
					if(specIds != null && specIds != ""){
						String[] specId1 = specIds.split(":");
						//计数器
						Integer num = 1;
						for (String specId:
								specId1) {
							//查询商品规格
							Map<String,Object> map5 = specItemsMapper.appFindSpecItems(specId);
							if(map5 != null && map5.size() > 0){
								String catName = (String) map5.get("catName");
								String itemName = (String) map5.get("itemName");
								if(num == specId1.length){
									specName += (catName+"："+itemName);
								}else {
									specName += (catName+"："+itemName+"@@_@@");
								}
							}
							num++;
						}
					}
				}
				map4.put("SpecName",specName);
			}
			//将购物车中这个店铺的商品添加到map的一个list集合中
			if(list2 != null && list2.size() > 0) {
				map.put("list", list2);
				list4.add(map);
			}
		}
		maps.put("code",1);
		maps.put("data",list4);
		return maps;
	}

	@Transactional
	@Override
	public Map<String, Object> appOrderPay(Integer userId, Integer addressId, Integer isInvoice, String invoiceClient, String orderRemarks) {
        Map<String,Object> map = new HashMap<String,Object>();
        try {
            List<String> list = new ArrayList<>();
            //先查询用户购物车中选中哪些商品
            List<Integer> goodsIds = sktCartsMapper.appFindIsCheck(userId);
            if(goodsIds == null || goodsIds.size() <= 0){
				map.put("code",0);
				map.put("status",-1);
				map.put("msg","购物车为空");
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return map;
			}
            //查询用户收货信息
            UsersAddress usersAddress = usersAddressMapper.selectById(addressId);
            if(usersAddress == null){
				map.put("code",0);
				map.put("status",-1);
				map.put("msg","地址不存在");
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return map;
			}
			//去重后的店铺
            Set<Integer> set = goodsService.appFindShopsByGoodsId(goodsIds);
			SimpleDateFormat sfDates = new SimpleDateFormat("yyyyMMddHHmmssSSS");
			String strDates = sfDates.format(new Date());
			String nums = GetOrderNum.getRandom620(2);
            String orderunique="2" + strDates + nums;
            //遍历店铺查询店铺下的商品
            for (Integer shopId:
                    set) {
                //一个店铺生成一个订单
                SktOrders sktOrders = new SktOrders();

                Map<String,Object> map2 = new HashMap<String,Object>();
                map2.put("userId",userId);
                map2.put("shopId",shopId);
                List<Map<String,Object>> goods = goodsMapper.appFindGoodsByshopId(map2);
                // 生成订单号
                SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                String strDate = sfDate.format(new Date());
                String num = GetOrderNum.getRandom620(2);
                sktOrders.setOrderNo("2" + strDate + num);
                String orderNo = "2" + strDate + num;
				rabbitSender.sendMessage(RabbitConstants.MQ_EXCHANGE_ORDER,RabbitConstants.MQ_ROUTING_KEY_ORDER,orderNo);
				String redisKey1 = "redis_key:orderNo:" + orderNo;
				cacheUtil.set(redisKey1,orderNo,Long.valueOf(60*30));
                sktOrders.setShopId(shopId);
                sktOrders.setUserId(userId);
                sktOrders.setOrderStatus(-2);
                sktOrders.setAreaId(usersAddress.getAreaId());
                String areaIdPath = usersAddress.getProvinceId()+"_"+usersAddress.getCityId()+"_"+usersAddress.getAreaId();
                sktOrders.setAreaIdPath(areaIdPath);
                sktOrders.setUserName(usersAddress.getUserName());
                sktOrders.setUserAddress(usersAddress.getUserAddress());
                sktOrders.setUserPhone(usersAddress.getUserPhone());
                sktOrders.setIsInvoice(isInvoice);
                if(invoiceClient != null && invoiceClient != ""){
                    sktOrders.setInvoiceClient(invoiceClient);
                }
                if(orderRemarks != null && orderRemarks != ""){
                    sktOrders.setOrderRemarks(orderRemarks);
                }
                sktOrders.setOrderunique(orderunique);
                //商品总金额
                BigDecimal goodsMoney = new BigDecimal(0);
				//商品总金额
				BigDecimal payShopping = new BigDecimal(0);
                //自营店铺支付积分
				Integer payScore = 0;
                //将商品信息存到集合中，方便一会生成ordergoods表
				List<SktOrderGoods> goodsList = new ArrayList<>();

                for (Map<String,Object> g:
                        goods) {
                	//商品id
					Integer goodsId = (Integer)g.get("goodsId");
					//是否有规格
					Integer isSpec = (Integer)g.get("isSpec");
					//商品数量
					Integer cartNum = (Integer) g.get("cartNum");

					/**
					 * 从数据库中取出库存，放到缓存中。
					 * 先判断缓存中有没有对应的库存
					 */
					// 库存ID
//        Integer goodsId  = sktCarts.getGoodsId();
					String redisKey = "redis_key:stock:" + goodsId;
					if(!cacheUtil.isKeyInCache(redisKey)){
						/**
						 * 缓存的数据格式
						 *redisKey:{
						 *     "goodsStock":goodsStock,
						 *     "isSpec":true/false,
						 *     "spec": {
						 *         specId:specStock,
						 *     }
						 *}
						 */
						JSONObject mmp = new JSONObject();

						Goods goods2 = new Goods();
						goods2 = goodsService.selectById(goodsId);
						mmp.put("goodsStock",goods2.getGoodsStock());
						if(isSpec.equals(0)){
							mmp.put("isSpec",false);
						}else{
							mmp.put("isSpec",true);
							JSONObject specsMap = new JSONObject();
							GoodsSpecs goodsSpecs1 =  new GoodsSpecs();
							goodsSpecs1.setGoodsId(goodsId);
							EntityWrapper<GoodsSpecs> entityWrapper =  new EntityWrapper<GoodsSpecs>(goodsSpecs1);
							List<GoodsSpecs> goodsSpecsList  = goodsSpecsService.selectList(entityWrapper);
							for(GoodsSpecs temp:goodsSpecsList){
								specsMap.put(temp.getId().toString(),temp.getSpecStock());
							}
							mmp.put("spec",specsMap);
						}

						cacheUtil.set(redisKey,mmp, Long.valueOf(60*30));
					};

					//商品单价
					BigDecimal goodsPrice = new BigDecimal(0);

					//商品总库存
					Integer goodsStock = 0;
					//判断商品是否有规格 如果有规格将规格数量存进去，没有就存商品数量
					if(isSpec == 1){
						//查询商品规格信息
						String goodsSpecId = (String)g.get("goodsSpecId");
						GoodsSpecs goodsSpecs = goodsSpecsMapper.selectById(goodsSpecId);
						goodsStock = goodsSpecs.getSpecStock();
						goodsPrice = goodsSpecs.getSpecPrice();


						//缓存要用的库存
						Integer Stock = 0;
						/**
						 * 从缓存中获取库存
						 */
//						String redisKey = "redis_key:stock:" + goodsId;

						JSONObject jsonObject = JSONObject.parseObject(cacheUtil.simpleGet(redisKey).toString());
						if(jsonObject.getBoolean("isSpec")){
							JSONObject spec = jsonObject.getJSONObject("spec");
							Stock = spec.getInteger(goodsSpecId);
						}else{
							Stock = jsonObject.getInteger("goodsStock");
						};

						//修改商品规格库存
						if(Stock < cartNum){
							//获取商品名称
							String goodsName = (String) g.get("goodsName");
							map.put("code",0);
							map.put("status",-1);
							map.put("msg","您购买的商品“"+goodsName+"”库存不足，无法购买");
							SktShops sktShops = sktShopsMapper.selectById(shopId);
							List<Integer> listt = new ArrayList<Integer>();
							listt.add(sktShops.getUserId());
							messagesService.addMessages(1,1,listt,"您的商品"+goodsName+"库存数量不足,请尽快补货",null);
							return map;
						}
						//修改规格库存
//						Integer integer = goodsSpecsMapper.updateById(goodsSpecs);
//						if(integer == 0){
//							map.put("code",0);
//							map.put("status",-1);
//							map.put("msg","失败");
//							return map;
//						}
					}else{
						goodsStock = (Integer) g.get("goodsStock");
						goodsPrice = (BigDecimal) g.get("shopPrice");
					}
					//一件商品的支付积分
					Integer onePayScore = (Integer)g.get("payScore");
					BigDecimal goodsPayShopping= new BigDecimal(g.get("payShopping").toString());
                    //一种商品的总金额
                    goodsMoney = goodsMoney.add(goodsPrice.multiply(new BigDecimal(cartNum)));
					payShopping=payShopping.add(goodsPayShopping.multiply(new BigDecimal(cartNum)));
                    //一种商品的支付积分
					payScore = payScore + (onePayScore * cartNum);
                    //判断商家库存是否充足
                    if(goodsStock < cartNum){
                    	//获取商品名称
						String goodsName = (String) g.get("goodsName");
						map.put("code",0);
						map.put("status",-1);
						map.put("msg","您购买的商品“"+goodsName+"”库存不足，无法购买");
						SktShops sktShops = sktShopsMapper.selectById(shopId);
						List<Integer> listt = new ArrayList<Integer>();
						listt.add(sktShops.getUserId());
						messagesService.addMessages(1,1,listt,"您的商品"+goodsName+"库存数量不足,请尽快补货",null);
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						return map;
					}
                    //修改库存
//                    Goods goods1 = new Goods();
//                    Integer goodsId = (Integer)g.get("goodsId");
//                    goods1.setGoodsId(goodsId);
//                    goods1.setGoodsStock(goodsStock - cartNum);
//					Integer integer1 = goodsMapper.updateById(goods1);
//					if(integer1 == 0){
//						map.put("code",0);
//						map.put("status",-1);
//						map.put("msg","失败");
//						return map;
//					}

					//存放ordergoods的实体类
                    SktOrderGoods sktOrderGoods = new SktOrderGoods();
                    //将商品id存到orderGoods中
					sktOrderGoods.setGoodsId(goodsId);
					//商品数量
					sktOrderGoods.setGoodsNum(cartNum);
					//商品价格
					sktOrderGoods.setGoodsPrice(goodsPrice.multiply(new BigDecimal(cartNum)));
					//自营店铺的商品支付的积分
					sktOrderGoods.setPayScore(onePayScore * cartNum);
					//积分赠送比例
					Integer scoreRatio = (Integer)g.get("scoreRatio");
					sktOrderGoods.setScoreRatio(scoreRatio);
					//赠送积分
					sktOrderGoods.setScore(sktOrderGoods.getGoodsPrice().multiply(new BigDecimal(scoreRatio)));
					//商品-规格ID
					String goodsSpecId = (String)g.get("goodsSpecId");
					sktOrderGoods.setGoodsSpecId(goodsSpecId);
					//商品-规格值列表
					sktOrderGoods.setGoodsSpecNames(null);
					//商品名称
					String goodsName = (String)g.get("goodsName");
					sktOrderGoods.setGoodsName(goodsName);
					//商品图
					String goodsImg = (String)g.get("goodsImg");
					sktOrderGoods.setGoodsImg(goodsImg);
					goodsList.add(sktOrderGoods);

					/**
					 *减少缓存的中的库存
					 */
//					String redisKey = "redis_key:stock:" + goodsId;
					JSONObject jsonObject = JSONObject.parseObject(cacheUtil.simpleGet(redisKey).toString());
					if (jsonObject.getBoolean("isSpec")) {
						jsonObject.put("goodsStock", jsonObject.getInteger("goodsStock") - cartNum);
						JSONObject specObj = jsonObject.getJSONObject("spec");
						specObj.put(goodsSpecId, specObj.getInteger(goodsSpecId) - cartNum);
					} else {
						jsonObject.put("goodsStock", jsonObject.getInteger("goodsStock") - cartNum);
					}
					cacheUtil.set(redisKey, jsonObject, Long.valueOf(60 * 30));

					//删除购物车中的商品
					Integer cartId = (Integer)g.get("cartId");
					Integer integer = sktCartsMapper.deleteById(cartId);
					if(integer == 0){
						map.put("code",0);
						map.put("status",-1);
						map.put("msg","失败");
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						return map;
					}
				}
                Map<String,Object> map3 = new HashMap<String,Object>();
                map3.put("shopId",shopId);
                map3.put("areaId2",usersAddress.getCityId());
                //查询运费
                SktShopFreights freigth = sktShopFreightsMapper.getFreigth(map3);
              if(freigth!=null){
				  sktOrders.setDeliverMoney(new BigDecimal(freigth.getFreight()));
			  }else {
				  sktOrders.setDeliverMoney(new BigDecimal(0));
			  }
			 	sktOrders.setPayScore(payScore);
                sktOrders.setGoodsMoney(goodsMoney);
				//订单总金额   goodsMoney + deliverMoney
				sktOrders.setTotalMoney(goodsMoney.add(sktOrders.getDeliverMoney()));
				sktOrders.setTotalShopping(payShopping);
				sktOrders.setCreateTime(new Date());
                Integer insert = sktOrdersMapper.insert(sktOrders);
				if(insert == 0){
					map.put("code",0);
					map.put("status",-1);
					map.put("msg","失败");
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return map;
				}
				SktShops sktShops = sktShopsMapper.selectById(shopId);
				List<Integer> listt = new ArrayList<Integer>();
				listt.add(sktShops.getUserId());
				messagesService.addMessages(1,1,listt,"您有一笔新的订单【"+sktOrders.getOrderNo()+"】待处理.",null);
				for (SktOrderGoods s:
						goodsList) {
					s.setOrderId(sktOrders.getOrderId());
				}
				boolean b = sktOrderGoodsService.insertBatch(goodsList);
				if(!b){
					map.put("code",0);
					map.put("status",-1);
					map.put("msg","失败");
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return map;
				}
				Integer orderId = sktOrders.getOrderId();
              //  list.add(sktOrders.getOrderNo());
            }

			for (Integer shopId:
					set) {
				Map<String,Object> map2 = new HashMap<String,Object>();
				map2.put("userId",userId);
				map2.put("shopId",shopId);
				List<Map<String,Object>> goods = goodsMapper.appFindGoodsByshopId(map2);

			}

            map.put("code",1);
			map.put("status",1);
            map.put("list",orderunique);

            return map;
        }catch (Exception e){
			e.printStackTrace();
            map.put("code",0);
			map.put("status",-1);
            map.put("msg","生成订单失败！");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return map;
        }
	}

    @Override
    public Map<String, Object> appAccountConfig(Integer userId, String code) {
		Map<String,Object> map = new HashMap<String,Object>();
	   try {
		   //查询用户账户的各种余额
		   Map<String,Object> account = accountMapper.appFindAccountByUserId(userId);
		   //查询支付场景
		   Map<String,Object> payscene = paySceneMapper.appFindPayScene(code);
		   map.put("account",account);
		   map.put("payscene",payscene);
		   map.put("code",1);
		   return map;
	   }catch (Exception e){
	   	map.put("code",0);
	   	map.put("msg","查询失败");
	   	return map;
	   }
    }


	@Override
	public Map<String, Object> appPayCashKaiyuan(Integer userId,Integer payType, String orderNo, Integer isBatch) {
	    Map<String,Object> mmp = new HashMap<String,Object>();
		List<String> lists=new ArrayList<>();
		BigDecimal payMoney =BigDecimal.ZERO;
		if (isBatch==0){
			SktOrders	sktOrders = sktOrdersMapper.appFindOrderByOrderNo(orderNo);
			lists.add(Integer.toString(sktOrders.getOrderId()));
			payMoney = sktOrders.getTotalMoney();
		}else {
			List<SktOrders> sktOrdersList = sktOrdersMapper.findOrdersByOrderunique(orderNo);
			if(sktOrdersList!=null&& sktOrdersList.size()>0){
				for (SktOrders orders:sktOrdersList){
					lists.add(Integer.toString(orders.getOrderId()));
					payMoney=payMoney.add(orders.getTotalMoney());
				}
			}else{
				mmp.put("code",00);
				mmp.put("msg","无此流水号对应订单");
				return mmp;
			}
		}

	    BigDecimal feeMoney = new BigDecimal(0);
	    //商品总金额
     //   BigDecimal goodsMoney = sktOrders.getGoodsMoney();
        if(payType == 3){
            //查询华宝支付手续费
            SktSysConfigs kaiyuanFee = sysConfigsMapper.selectSysConfigsByFieldCode("kaiyuanFee");
            BigDecimal huaBaoFee = new BigDecimal(kaiyuanFee.getFieldValue());
            //综合服务费
            SktSysConfigs taxRatio = sysConfigsMapper.selectSysConfigsByFieldCode("taxRatio");
            BigDecimal taxRatio2 = new BigDecimal(taxRatio.getFieldValue());
            feeMoney = payMoney.multiply(huaBaoFee).add(payMoney.multiply(taxRatio2));
        }
        if(payType == 6){
            //华宝货款手续费
            SktSysConfigs kaiyuanturnFee = sysConfigsMapper.selectSysConfigsByFieldCode("kaiyuanturnFee");
            BigDecimal huaBaoTurnFee = new BigDecimal(kaiyuanturnFee.getFieldValue());
            feeMoney = payMoney.multiply(huaBaoTurnFee);
        }
//	    List<String> lists = new ArrayList<String>();
//	    lists.add(sktOrders.getOrderId().toString());
        Map<String, Object> map = accountService.userSale(lists,payType,payMoney,feeMoney,userId);
        if("01".equals(map.get("code").toString())){
//			sktOrders.setPaymentTime(new Date());
//			sktOrdersMapper.updateById(sktOrders);
            mmp.put("code", "01");
            mmp.put("orderNo", orderNo);
            mmp.put("payMoney",payMoney);
            mmp.put("createTime",new Date());
        }else{
            mmp.put("code", "00");
            mmp.put("msg", "失败");
        }
		return mmp;
	}

	/**
	 *自营店铺华宝华 宝货款支付  优惠券支付
	 * @param userId
	 * @param payType
	 * @param orderNo
	 * @param isBatch
     * @param thirdNo
	 * @return
	 */
	@Override
	public Map<String, Object> newAppPayCashKaiyuan(Integer userId,Integer payType, String orderNo, Integer isBatch,String thirdNo,Integer thirdType,String payName) {
		Map<String,Object> mmp = new HashMap<String,Object>();
		List<String> lists=new ArrayList<>();
		BigDecimal payMoney =BigDecimal.ZERO;
		BigDecimal payKaiyuan =BigDecimal.ZERO;
		BigDecimal payShopping =BigDecimal.ZERO;
		if (isBatch==0){
			SktOrders	sktOrders = sktOrdersMapper.appFindOrderByOrderNo(orderNo);
			lists.add(Integer.toString(sktOrders.getOrderId()));
			payMoney = sktOrders.getTotalMoney();
			payKaiyuan=sktOrders.getKaiyuan();
			payShopping=sktOrders.getTotalShopping();
		}else {
			List<SktOrders> sktOrdersList = sktOrdersMapper.findOrdersByOrderunique(orderNo);
			if(sktOrdersList!=null&& sktOrdersList.size()>0){
				for (SktOrders orders:sktOrdersList){
					lists.add(Integer.toString(orders.getOrderId()));
					payMoney=payMoney.add(orders.getTotalMoney());
					payKaiyuan=payKaiyuan.add(orders.getKaiyuan());
					payShopping=payShopping.add(orders.getTotalShopping());
				}
			}else{
				mmp.put("code",00);
				mmp.put("msg","无此流水号对应订单");
				return mmp;
			}
		}

		BigDecimal feeKaiyuan = new BigDecimal(0);
		//商品总金额
		//   BigDecimal goodsMoney = sktOrders.getGoodsMoney();
		if(payType == 7){
			//查询华宝支付手续费
			SktSysConfigs kaiyuanFee = sysConfigsMapper.selectSysConfigsByFieldCode("kaiyuanFee");
			BigDecimal huaBaoFee = new BigDecimal(kaiyuanFee.getFieldValue());
			//综合服务费
			SktSysConfigs taxRatio = sysConfigsMapper.selectSysConfigsByFieldCode("taxRatio");
			BigDecimal taxRatio2 = new BigDecimal(taxRatio.getFieldValue());
			feeKaiyuan = payKaiyuan.multiply(huaBaoFee).add(payKaiyuan.multiply(taxRatio2)).multiply(new BigDecimal(0.01));
		}
		if(payType == 8){
			//华宝货款手续费
			SktSysConfigs kaiyuanturnFee = sysConfigsMapper.selectSysConfigsByFieldCode("kaiyuanturnFee");
			BigDecimal huaBaoTurnFee = new BigDecimal(kaiyuanturnFee.getFieldValue());
			feeKaiyuan = payKaiyuan.multiply(huaBaoTurnFee).multiply(new BigDecimal(0.01));
		}
//	    List<String> lists = new ArrayList<String>();
//	    lists.add(sktOrders.getOrderId().toString());
		Map<String, Object> map = accountService.payment(lists,userId,payType,payMoney,payKaiyuan,feeKaiyuan,payShopping,thirdNo,thirdType,payName);
		if("01".equals(map.get("code").toString())){
//			sktOrders.setPaymentTime(new Date());
//			sktOrdersMapper.updateById(sktOrders);
			mmp.put("code", "01");
			mmp.put("orderNo", orderNo);
			mmp.put("payMoney",payMoney);
			mmp.put("createTime",new Date());
		}else{
			mmp.put("code", "00");
			mmp.put("msg", map.get("msg").toString());
		}
		return mmp;
	}
	@Override
	public Map<String, Object> appCheckCarts(Integer userId) {
		Map<String,Object> maps = new HashMap<String,Object>();
		try {
			SktCarts sktCarts=new SktCarts();
			sktCarts.setUserId(userId);
			EntityWrapper<SktCarts> entityWrapper=new EntityWrapper<SktCarts>(sktCarts);
			List<SktCarts> sktCartsList = this.selectList(entityWrapper);
			if (sktCartsList!=null && sktCartsList.size()>0){
				for (SktCarts cart:sktCartsList){
					Integer goodsId=cart.getGoodsId();
					Map<String, Object> map = goodsService.checkGoodsAndShop(goodsId);
					if("0".equals(map.get("code").toString())){
						maps.put("code",0);
						maps.put("msg",map.get("msg").toString());
						return  maps;
					}
				}
			}
			List<Map<String,Object>> list4 = new ArrayList<Map<String,Object>>();
			//获取用户默认地址
			AppUserAddressDTO resultAdd = usersAddressMapper.appFindAddress(userId);
			if(resultAdd == null){
				maps.put("address",new UsersAddressDTO());
			}else{
				resultAdd.setAreaId(resultAdd.getCityId());
				Map<String,Object> address = new HashMap<String,Object>();
				address.put("userName",resultAdd.getUserName());
				address.put("userPhone",resultAdd.getUserPhone());
				address.put("provinceId",resultAdd.getProvinceId());
				address.put("cityId",resultAdd.getCityId());
				address.put("areaId",resultAdd.getAreaId());
				address.put("userAddress",resultAdd.getUserAddress());
				address.put("isDefault",resultAdd.getIsDefault());
				address.put("addressId",resultAdd.getAddressId());
				address.put("areaId2",resultAdd.getCityId());
				SktAreas sktAreasProvince = sktAreasService.selectById(resultAdd.getProvinceId());
				String provinceName=sktAreasProvince.getAreaName();
				SktAreas sktAreasCity = sktAreasService.selectById(resultAdd.getCityId());
				String cityName = sktAreasCity.getAreaName();
				SktAreas sktAreasArea = sktAreasService.selectById(resultAdd.getAreaId());
				String areaName = sktAreasArea.getAreaName();
				String name=provinceName+cityName+areaName;
				address.put("name",name);
				maps.put("address",address);
			}
			//先查询用户选中的商品在那几个店铺(去重)
			List<Map<String,Object>> list = sktShopsMapper.appFindCheckShops(userId);
			//如果用户有默认地址，查询商家在本地区运费
			//市id
			Integer areaId2 = 0;
			//总运费
			Integer allAddressPrice = 0;
			//总价
			BigDecimal allPrice = new BigDecimal(0);
			//总华宝
			BigDecimal allPayKaiyuan = new BigDecimal(0);
			//总购物券
			BigDecimal allPayShopping = new BigDecimal(0);
			if(resultAdd != null){
				areaId2 = resultAdd.getAreaId();
			}
			for (Map<String,Object> map2:
					list) {
				Map<String,Object> map = new HashMap<String,Object>();
				//将店铺名称存到map中
				String shopName = (String)map2.get("shopName");
				map.put("catName",shopName);
				Map<String,Object> map3 = new HashMap<String,Object>();
				Integer shopId = (Integer)map2.get("shopId");
				//通过shopId查询运费
				if(areaId2 != 0){
					Map<String,Object> map5 = new HashMap<String,Object>();
					map5.put("shopId",shopId);
					map5.put("areaId2",areaId2);
					SktShopFreights freigth = sktShopFreightsMapper.getFreigth(map5);
					if (freigth != null){
						allAddressPrice += freigth.getFreight();
					}
				}

				map3.put("shopId",shopId);
				map3.put("userId",userId);
				//通过店铺id查询用户购物车中这个店铺的商品
				List<Map<String,Object>> list2 = sktCartsMapper.appFindGoodsByShopId(map3);
				//遍历一个店铺下的所有商品

				for (Map<String,Object> map4:
						list2) {
					BigDecimal payShopping = new BigDecimal(map4.get("payShopping").toString());
					//用于拼接商品规格字符串
					String specName = "";
					//判断是否有规格
					Integer isSpec = (Integer)map4.get("isSpec");
					if(isSpec == 1){
						//获得单个商品价格
						BigDecimal specPrice = (BigDecimal) map4.get("specPrice");

						//获取商品数量
						Integer cartNum = (Integer) map4.get("cartNum");


						//这个商品总价
						if(specPrice!=null){
							allPrice = allPrice.add(specPrice.multiply(new BigDecimal(cartNum)));
						}else{
							BigDecimal shopPrice=new BigDecimal(map4.get("shopPrice").toString());
							map4.put("specPrice",shopPrice);
							map4.put("specStock","0");
							map4.put("specIds","0");
							allPrice = allPrice.add(shopPrice.multiply(new BigDecimal(cartNum)));
						}
						allPayKaiyuan=allPayKaiyuan.add(allPayKaiyuan.multiply(new BigDecimal(cartNum)));
						allPayShopping=allPayShopping.add(payShopping.multiply(new BigDecimal(cartNum)));
						String specIds = (String)map4.get("specIds");
						if(specIds != null && specIds != ""){
							String[] specId1 = specIds.split(":");
							//计数器
							Integer num = 1;
							for (String specId:
									specId1) {
								//查询商品规格
								Map<String,Object> map5 = specItemsMapper.appFindSpecItems(specId);
								if(map5 != null && map5.size() > 0){
									String catName = (String) map5.get("catName");
									String itemName = (String) map5.get("itemName");
									if(num == specId1.length){
										specName += (catName+"："+itemName);
									}else {
										specName += (catName+"："+itemName+"@@_@@");
									}
								}
								num++;
							}
						}
					}else{
						//获得单个商品价格
						BigDecimal shopPrice = (BigDecimal) map4.get("shopPrice");
						//获取商品数量
						Integer cartNum = (Integer) map4.get("cartNum");
						//这个商品总价
						allPrice = allPrice.add(shopPrice.multiply(new BigDecimal(cartNum)));
						allPayKaiyuan = allPayKaiyuan.add(allPayKaiyuan.multiply(new BigDecimal(cartNum)));
						allPayShopping = allPayShopping.add(payShopping.multiply(new BigDecimal(cartNum)));

						map4.put("specPrice",shopPrice);
					}
					map4.put("SpecName",specName);
					map4.put("allPayKaiyuan",allPayKaiyuan);
					map4.put("allPayShopping",allPayShopping);
				}
				//将购物车中这个店铺的商品添加到map的一个list集合中
				if(list2 != null && list2.size() > 0) {
					map.put("list", list2);
					list4.add(map);
				}
			}
			//总运费
			maps.put("allAddressPrice",allAddressPrice);
			//总购物券
			maps.put("allPayShopping",allPayShopping);
			//商品总价
			maps.put("allPrice",allPrice.add(new BigDecimal(allAddressPrice)));
			maps.put("goodsList",list4);
			maps.put("code",1);
			return maps;
		}catch (Exception e){
			e.printStackTrace();
			maps.put("code",0);
			maps.put("msg","查询出错");
			return maps;
		}
	}

	@Override
	@Transactional
	public Map<String, Object> updateCartNum(String cartId, String cartNum) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			//查询购物车有没有此数据
			SktCarts sktCarts1 = sktCartsMapper.selectById(cartId);
			if(sktCarts1 == null){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				map.put("code","00");
				map.put("msg","购物车没有查到此商品");
				return map;
			}
			SktCarts sktCarts = new SktCarts();
			sktCarts.setCartId(Integer.parseInt(cartId));
			sktCarts.setCartNum(Integer.parseInt(cartNum));
			//更新数量
			Integer integer = sktCartsMapper.updateById(sktCarts);
			if(integer.equals(0)){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				map.put("code","00");
				map.put("msg","更新数量失败");
				return map;
			}
			map.put("code","01");
			map.put("msg","成功");
			return map;
		}catch (Exception e){
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			map.put("code","00");
			map.put("msg","错误");
			return map;
		}
	}

	public List removeDuplicate(List list) {
		HashSet h = new HashSet(list);
		list.clear();
		list.addAll(h);
		return list;
	}

	@Override
	public Integer appnewAddressBuy(Integer shopId, Integer areaId2) {
		Map<String,Integer> mmp = new HashMap<String,Integer>();
		mmp.put("shopId",shopId);
		mmp.put("areaId2",areaId2);
		// TODO Auto-generated method stub
		return sktCartsMapper.appnewAddressBuy(mmp);
	}

	@Override
	public Map<String,Object> newAddressPrice(Integer userId, Integer areaId2) {
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			//先查询用户选中的商品在那几个店铺(去重)
			List<Map<String,Object>> list = sktShopsMapper.appFindCheckShops(userId);
			//总运费
			Integer allAddressPrice = 0;
			//总价
			BigDecimal allPrice = new BigDecimal(0);
			for (Map<String,Object> map2:
					list) {
				Map<String,Object> map3 = new HashMap<String,Object>();
				Integer shopId = (Integer)map2.get("shopId");
				//通过shopId查询运费
				if(areaId2 != 0){
					Map<String,Object> map5 = new HashMap<String,Object>();
					map5.put("shopId",shopId);
					map5.put("areaId2",areaId2);
					SktShopFreights freigth = sktShopFreightsMapper.getFreigth(map5);
					if (freigth != null){
						allAddressPrice += freigth.getFreight();
					}
				}

				map3.put("shopId",shopId);
				map3.put("userId",userId);
				//通过店铺id查询用户购物车中这个店铺的商品
				List<Map<String,Object>> list2 = sktCartsMapper.appFindGoodsByShopId(map3);
				//遍历一个店铺下的所有商品
				for (Map<String,Object> map4:
						list2) {
					//判断是否有规格
					Integer isSpec = (Integer)map4.get("isSpec");
					if(isSpec == 1){
						//获得单个商品价格
						BigDecimal specPrice = (BigDecimal) map4.get("specPrice");

						//获取商品数量
						Integer cartNum = (Integer) map4.get("cartNum");
						//这个商品总价
						if(specPrice!=null){
							allPrice = allPrice.add(specPrice.multiply(new BigDecimal(cartNum)));
						}else{
							BigDecimal shopPrice=new BigDecimal(map4.get("shopPrice").toString());
							allPrice = allPrice.add(shopPrice.multiply(new BigDecimal(cartNum)));
						}
					}else{
						//获得单个商品价格
						BigDecimal shopPrice = (BigDecimal) map4.get("shopPrice");
						//获取商品数量
						Integer cartNum = (Integer) map4.get("cartNum");
						//这个商品总价
						allPrice = allPrice.add(shopPrice.multiply(new BigDecimal(cartNum)));
					}
				}
			}
			map.put("code",1);
			map.put("allAddressPrice",allAddressPrice);
			map.put("allPrice",allPrice);
			return (map);
		}catch (Exception e){
			e.printStackTrace();
			map.put("code",0);
			map.put("msg","获取地址信息失败");
			return map;
		}
	}

	@Transactional
	@Override
	public Map<String, Object> h5appOrderPay(Integer userId, Integer addressId, Integer isInvoice, String invoiceClient, List<Map> orderRemarks) {
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			List<String> list = new ArrayList<>();
			//先查询用户购物车中选中哪些商品
			List<Integer> goodsIds = sktCartsMapper.appFindIsCheck(userId);
			if(goodsIds == null || goodsIds.size() <= 0){
				map.put("code",0);
				map.put("status",-1);
				map.put("msg","购物车为空");
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return map;
			}
			//查询用户收货信息
			UsersAddress usersAddress = usersAddressMapper.selectById(addressId);
			if(usersAddress == null){
				map.put("code",0);
				map.put("status",-1);
				map.put("msg","地址不存在");
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return map;
			}
			//去重后的店铺
			Set<Integer> set = goodsService.appFindShopsByGoodsId(goodsIds);
			SimpleDateFormat sfDates = new SimpleDateFormat("yyyyMMddHHmmssSSS");
			String strDates = sfDates.format(new Date());
			String nums = GetOrderNum.getRandom620(2);
			String orderunique="2" + strDates + nums;
			//遍历店铺查询店铺下的商品
			for (Integer shopId:
					set) {
				//一个店铺生成一个订单
				SktOrders sktOrders = new SktOrders();

				Map<String,Object> map2 = new HashMap<String,Object>();
				map2.put("userId",userId);
				map2.put("shopId",shopId);
				List<Map<String,Object>> goods = goodsMapper.appFindGoodsByshopId(map2);
				// 生成订单号
				SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
				String strDate = sfDate.format(new Date());
				String num = GetOrderNum.getRandom620(2);
				sktOrders.setOrderNo("2" + strDate + num);
				String orderNo = "2" + strDate + num;
				rabbitSender.sendMessage(RabbitConstants.MQ_EXCHANGE_ORDER,RabbitConstants.MQ_ROUTING_KEY_ORDER,orderNo);
				String redisKey1 = "redis_key:orderNo:" + orderNo;
				cacheUtil.set(redisKey1,orderNo,Long.valueOf(60*30));
				sktOrders.setShopId(shopId);
				sktOrders.setUserId(userId);
				sktOrders.setOrderStatus(-2);
				sktOrders.setAreaId(usersAddress.getAreaId());
				String areaIdPath = usersAddress.getProvinceId()+"_"+usersAddress.getCityId()+"_"+usersAddress.getAreaId();
				sktOrders.setAreaIdPath(areaIdPath);
				sktOrders.setUserName(usersAddress.getUserName());
				sktOrders.setUserAddress(usersAddress.getUserAddress());
				sktOrders.setUserPhone(usersAddress.getUserPhone());
				sktOrders.setIsInvoice(isInvoice);
				if(invoiceClient != null && invoiceClient != ""){
					sktOrders.setInvoiceClient(invoiceClient);
				}
				if(orderRemarks != null){
					for (Map mmp:
							orderRemarks) {
						Integer shopId1 = (Integer)mmp.get("shopId");
						if(shopId1.equals(shopId)){
							String orderRemark = (String)mmp.get("orderRemark");
							sktOrders.setOrderRemarks(orderRemark);
						}
					}
				}else{
					sktOrders.setOrderRemarks(null);
				}
				sktOrders.setOrderunique(orderunique);
				//商品总金额
				BigDecimal goodsMoney = new BigDecimal(0);
				//自营店铺支付积分
				Integer payScore = 0;
				//将商品信息存到集合中，方便一会生成ordergoods表
				List<SktOrderGoods> goodsList = new ArrayList<>();

				for (Map<String,Object> g:
						goods) {

					//商品id
					Integer goodsId = (Integer)g.get("goodsId");
					//是否有规格
					Integer isSpec = (Integer)g.get("isSpec");
					//商品数量
					Integer cartNum = (Integer) g.get("cartNum");

					/**
					 * 从数据库中取出库存，放到缓存中。
					 * 先判断缓存中有没有对应的库存
					 */
					// 库存ID
//        Integer goodsId  = sktCarts.getGoodsId();
					String redisKey = "redis_key:stock:" + goodsId;
					if(!cacheUtil.isKeyInCache(redisKey)){
						/**
						 * 缓存的数据格式
						 *redisKey:{
						 *     "goodsStock":goodsStock,
						 *     "isSpec":true/false,
						 *     "spec": {
						 *         specId:specStock,
						 *     }
						 *}
						 */
						JSONObject mmp = new JSONObject();

						Goods goods2 = new Goods();
						goods2 = goodsService.selectById(goodsId);
						mmp.put("goodsStock",goods2.getGoodsStock());
						if(isSpec.equals(0)){
							mmp.put("isSpec",false);
						}else{
							mmp.put("isSpec",true);
							JSONObject specsMap = new JSONObject();
							GoodsSpecs goodsSpecs1 =  new GoodsSpecs();
							goodsSpecs1.setGoodsId(goodsId);
							EntityWrapper<GoodsSpecs> entityWrapper =  new EntityWrapper<GoodsSpecs>(goodsSpecs1);
							List<GoodsSpecs> goodsSpecsList  = goodsSpecsService.selectList(entityWrapper);
							for(GoodsSpecs temp:goodsSpecsList){
								specsMap.put(temp.getId().toString(),temp.getSpecStock());
							}
							mmp.put("spec",specsMap);
						}

						cacheUtil.set(redisKey,mmp, Long.valueOf(60*30));
					};

					//商品单价
					BigDecimal goodsPrice = new BigDecimal(0);
					//
					//商品总库存
					Integer goodsStock = 0;
					//判断商品是否有规格 如果有规格将规格数量存进去，没有就存商品数量
					if(isSpec == 1){
						//查询商品规格信息
						String goodsSpecId = (String)g.get("goodsSpecId");
						GoodsSpecs goodsSpecs = goodsSpecsMapper.selectById(goodsSpecId);
							goodsStock = goodsSpecs.getSpecStock();
							goodsPrice = goodsSpecs.getSpecPrice();

						//缓存要用的库存
						Integer Stock = 0;
						/**
						 * 从缓存中获取库存
						 */
//						String redisKey = "redis_key:stock:" + goodsId;

						JSONObject jsonObject = JSONObject.parseObject(cacheUtil.simpleGet(redisKey).toString());
						if(jsonObject.getBoolean("isSpec")){
							JSONObject spec = jsonObject.getJSONObject("spec");
							Stock = spec.getInteger(goodsSpecId);
						}else{
							Stock = jsonObject.getInteger("goodsStock");
						};

						//修改商品规格库存
						if(Stock < cartNum){
							//获取商品名称
							String goodsName = (String) g.get("goodsName");
							map.put("code",0);
							map.put("status",-1);
							map.put("msg","您购买的商品“"+goodsName+"”库存不足，无法购买");
							SktShops sktShops = sktShopsMapper.selectById(shopId);
							List<Integer> listt = new ArrayList<Integer>();
							listt.add(sktShops.getUserId());
							messagesService.addMessages(1,1,listt,"您的商品"+goodsName+"库存数量不足,请尽快补货",null);
							return map;
						}
						//修改规格库存
//						Integer integer = goodsSpecsMapper.updateById(goodsSpecs);
//						if(integer == 0){
//							map.put("code",0);
//							map.put("status",-1);
//							map.put("msg","失败");
//							return map;
//						}
					}else{
						goodsStock = (Integer) g.get("goodsStock");
						goodsPrice = (BigDecimal) g.get("shopPrice");
					}
					//一件商品的支付积分
					Integer onePayScore = (Integer)g.get("payScore");

					//一种商品的总金额
					goodsMoney = goodsMoney.add(goodsPrice.multiply(new BigDecimal(cartNum)));
					//一种商品的支付积分
					payScore = payScore + (onePayScore * cartNum);
					//判断商家库存是否充足
					if(goodsStock < cartNum){
						//获取商品名称
						String goodsName = (String) g.get("goodsName");
						map.put("code",0);
						map.put("status",-1);
						map.put("msg","您购买的商品“"+goodsName+"”库存不足，无法购买");
						SktShops sktShops = sktShopsMapper.selectById(shopId);
						List<Integer> listt = new ArrayList<Integer>();
						listt.add(sktShops.getUserId());
						messagesService.addMessages(1,1,listt,"您的商品"+goodsName+"库存数量不足,请尽快补货",null);
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						return map;
					}
					//修改库存
//                    Goods goods1 = new Goods();
//                    Integer goodsId = (Integer)g.get("goodsId");
//                    goods1.setGoodsId(goodsId);
//                    goods1.setGoodsStock(goodsStock - cartNum);
//					Integer integer1 = goodsMapper.updateById(goods1);
//					if(integer1 == 0){
//						map.put("code",0);
//						map.put("status",-1);
//						map.put("msg","失败");
//						return map;
//					}

					//存放ordergoods的实体类
					SktOrderGoods sktOrderGoods = new SktOrderGoods();
					//将商品id存到orderGoods中
					sktOrderGoods.setGoodsId(goodsId);
					//商品数量
					sktOrderGoods.setGoodsNum(cartNum);
					//商品价格
					sktOrderGoods.setGoodsPrice(goodsPrice.multiply(new BigDecimal(cartNum)));
					//自营店铺的商品支付的积分
					sktOrderGoods.setPayScore(onePayScore * cartNum);
					//积分赠送比例
					Integer scoreRatio = (Integer)g.get("scoreRatio");
					sktOrderGoods.setScoreRatio(scoreRatio);
					//赠送积分
					sktOrderGoods.setScore(sktOrderGoods.getGoodsPrice().multiply(new BigDecimal(scoreRatio)));
					//商品-规格ID
					String goodsSpecId = (String)g.get("goodsSpecId");
					sktOrderGoods.setGoodsSpecId(goodsSpecId);
					//商品-规格值列表
					sktOrderGoods.setGoodsSpecNames(null);
					//商品名称
					String goodsName = (String)g.get("goodsName");
					sktOrderGoods.setGoodsName(goodsName);
					//商品图
					String goodsImg = (String)g.get("goodsImg");
					sktOrderGoods.setGoodsImg(goodsImg);
					goodsList.add(sktOrderGoods);

					/**
					 *减少缓存的中的库存
					 */
//					String redisKey = "redis_key:stock:" + goodsId;
					JSONObject jsonObject = JSONObject.parseObject(cacheUtil.simpleGet(redisKey).toString());
					if (jsonObject.getBoolean("isSpec")) {
						jsonObject.put("goodsStock", jsonObject.getInteger("goodsStock") - cartNum);
						JSONObject specObj = jsonObject.getJSONObject("spec");
						specObj.put(goodsSpecId, specObj.getInteger(goodsSpecId) - cartNum);
					} else {
						jsonObject.put("goodsStock", jsonObject.getInteger("goodsStock") - cartNum);
					}
					cacheUtil.set(redisKey, jsonObject, Long.valueOf(60 * 30));

					//删除购物车中的商品
					Integer cartId = (Integer)g.get("cartId");
					Integer integer = sktCartsMapper.deleteById(cartId);
					if(integer == 0){
						map.put("code",0);
						map.put("status",-1);
						map.put("msg","失败");
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						return map;
					}
				}
				Map<String,Object> map3 = new HashMap<String,Object>();
				map3.put("shopId",shopId);
				map3.put("areaId2",usersAddress.getCityId());
				//查询运费
				SktShopFreights freigth = sktShopFreightsMapper.getFreigth(map3);
				if(freigth!=null){
					sktOrders.setDeliverMoney(new BigDecimal(freigth.getFreight()));
				}else {
					sktOrders.setDeliverMoney(new BigDecimal(0));
				}
				sktOrders.setPayScore(payScore);
				sktOrders.setGoodsMoney(goodsMoney);
				//订单总金额   goodsMoney + deliverMoney
				sktOrders.setTotalMoney(goodsMoney.add(sktOrders.getDeliverMoney()));
				sktOrders.setCreateTime(new Date());
				Integer insert = sktOrdersMapper.insert(sktOrders);
				if(insert == 0){
					map.put("code",0);
					map.put("status",-1);
					map.put("msg","失败");
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return map;
				}
				SktShops sktShops = sktShopsMapper.selectById(shopId);
				List<Integer> listt = new ArrayList<Integer>();
				listt.add(sktShops.getUserId());
				messagesService.addMessages(1,1,listt,"您有一笔新的订单【"+sktOrders.getOrderNo()+"】待处理.",null);
				for (SktOrderGoods s:
						goodsList) {
					s.setOrderId(sktOrders.getOrderId());
				}
				boolean b = sktOrderGoodsService.insertBatch(goodsList);
				if(!b){
					map.put("code",0);
					map.put("status",-1);
					map.put("msg","失败");
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return map;
				}
				Integer orderId = sktOrders.getOrderId();
				//  list.add(sktOrders.getOrderNo());
			}

			for (Integer shopId:
					set) {
				Map<String,Object> map2 = new HashMap<String,Object>();
				map2.put("userId",userId);
				map2.put("shopId",shopId);
				List<Map<String,Object>> goods = goodsMapper.appFindGoodsByshopId(map2);

			}

			map.put("code",1);
			map.put("status",1);
			map.put("list",orderunique);

			return map;
		}catch (Exception e){
			e.printStackTrace();
			map.put("code",0);
			map.put("status",-1);
			map.put("msg","生成订单失败！");
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return map;
		}
	}

}
